package pdf;

import com.alibaba.excel.EasyExcel;
import excel.ExcelDto;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liangpei
 * @date 2021/11/23 16:00
 * @description 解析报关单  中远盛宣  欧普光学
 */
public class OupuGuangXue {
    public static void main(String[] args) {
        /*String filePath = "/Users/liangpei/Documents/pdf/（已压缩）报关单202401.pdf";
        parse(new File(filePath), "/Users/liangpei/Documents/pdf/");*/

        // 获取 JAR 文件所在目录
        //String jarPath = new File(PdfTest.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent();
        File pdfDirectory = new File("E:\\pdf");
        // 获取目录下的所有PDF文件
        File[] pdfFiles = pdfDirectory.listFiles((dir, name) -> name.toLowerCase().endsWith(".pdf"));
        if (pdfFiles != null) {
            for (File file : pdfFiles) {
                System.out.println("正在处理文件: " + file.getName());
                parseTxt(file, "E:\\pdf");
                //parsePic(file, "/Users/liangpei/Documents/pdf/");
            }
        } else {
            System.out.println("没有找到 PDF 文件。");
        }
        System.out.println("处理完成。");
    }
    /*public static void main(String[] args) {
        String filePath = "/Users/liangpei/Documents/pdf/（已压缩）报关单202401.pdf";
        parse(new File(filePath), "/Users/liangpei/Documents/pdf/");
    }*/

    public static void parseTxt(File file, String jarPath) {
        //File file = new File(filePath);
        try (PDDocument document = Loader.loadPDF(file)) {
            //获取总页数
            int pageCount = document.getNumberOfPages();
            System.out.println("PDF 总页数：" + pageCount);

            List<ExcelDto> excelDtoList = new ArrayList<ExcelDto>();

            //循环读取
            for (int i = 1; i <= pageCount; i++) {
                //获取指定页
                PDFTextStripper stripper = new PDFTextStripper();
                stripper.setStartPage(i);
                stripper.setEndPage(i);
                String text = stripper.getText(document);


                // 提取海关编号
                String firstLineData = "";
                firstLineData = extractCustomsNumber(text);
                System.out.println("海关编号: " + firstLineData);

                // 正则表达式匹配商品信息
                String regex = "(\\d+)\\s+(\\d+)\\s+[\\s\\S]+?\\s+(\\d+\\.?\\d*)\\s+(\\d+\\.?\\d*)\\s+(\\w{3})";

                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(text);
                while (matcher.find()) {
                    ExcelDto excelDto = new ExcelDto();
                    String productNumber = matcher.group(2);
                    String totalPrice = matcher.group(4);
                    String currency = matcher.group(5);


                    System.out.println("商品编号: " + productNumber);
                    System.out.println("总价: " + totalPrice);
                    System.out.println("币制: " + currency);
                    excelDto.setNo(firstLineData);
                    excelDto.setType(currency);
                    excelDto.setAmount(totalPrice);
                    excelDto.setGoodsNo(productNumber);


                    excelDtoList.add(excelDto);
                }

            }
            String fileName = file.getName().replace(".pdf", ".xlsx");


            String excelPath = jarPath + File.separator + "excel" + File.separator + fileName;
            System.out.println("正在生成 Excel 文件: " + excelPath);
            // 确保目标目录存在
            File excelDir = new File(jarPath + File.separator + "excel");
            if (!excelDir.exists()) {
                boolean mkdirsSuccess = excelDir.mkdirs();
                if (mkdirsSuccess) {
                    //System.out.println("目录创建成功: " + excelDir.getAbsolutePath());
                } else {
                    //System.err.println("目录创建失败: " + excelDir.getAbsolutePath());
                    return;
                }
            }


            EasyExcel.write(new File(excelPath), ExcelDto.class)
                    //.registerWriteHandler(new CustomMergeStrategy(0))
                    .sheet("报关单")
                    .doWrite(excelDtoList);
        } catch (Exception e) {
            System.out.println("处理文件 " + file.getName() + " 出错。");
            e.printStackTrace();
        }
    }


    private static String extractCustomsNumber(String text) {
        // 正则表达式匹配海关编号
        String regex = "海关编号：(\\d+)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

    private static void extractProductInfo(String text) {
        // 正则表达式匹配商品信息
        String regex = "(\\d+)\\s+(\\d+)\\s+[\\s\\S]+?\\s+(\\d+\\.?\\d*)\\s+(\\d+\\.?\\d*)\\s+(\\w{3})";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        if (matcher.find()) {
            String productNumber = matcher.group(2);
            String totalPrice = matcher.group(4);
            String currency = matcher.group(5);


            System.out.println("商品编号: " + productNumber);
            System.out.println("总价: " + totalPrice);
            System.out.println("币制: " + currency);
        } else {
            System.out.println("商品信息解析失败，未找到匹配项。");
        }
    }

}
